package cn.bellychang.whiteboard;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ChangLiang
 * @date 2021/3/11
 */
public class CollectIntegerSolution {

    private static final int MAX_RECURSIVE_DEPTH = 50;

    private int depth= 0;

    public List<Integer> collectInteger(Object list) {
        List<Integer> result = new ArrayList<>();
        collectInteger(list, result);
        return result;
    }

    private void collectInteger(Object obj, List<Integer> result) {
        depth++;
        if (depth >= MAX_RECURSIVE_DEPTH) {
            throw new RuntimeException("stack depth exceeds max recursive depth");
        }
        if (obj instanceof Integer) {
            result.add((Integer) obj);
            return;
        } else {
            List<Integer> list = (List<Integer>) obj;
            for (int i = 0; i < list.size(); i++) {
                collectInteger(list.get(i), result);
            }
        }
    }
}
